﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Axial.Reflection;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Axial
{
	public class WFValidator : WFScript, IValidator
	{
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			Page.Validators.Add(this);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			Page.Form.Attributes["onsubmit"] = "return " + MethodName + "();";
		}

		public string ErrorMessage { get; set; }
		public bool IsValid { get; set; }
		public void Validate()
		{
			MethodInfo method = Page.GetMethod(MethodName);
			if (method == null)
				throw new ArgumentException("Method " + MethodName + " not found in the page");
			if (method.ReturnType != typeof(bool) || method.GetParameters().Length > 0)
				throw new ArgumentException("Method " + MethodName + " must take no parameters and return a bool");
			IsValid = (bool)method.Invoke(Page, null);
		}
	}
}
